<template>
  <div class="view-fill">
    <div
      v-if="
        !modifyInfo.visible &&
        !modifyReceiveInfo.visible &&
        !modifyByContractInfo.visible &&
        !buildAssetCardInfo.visible &&
        !modifySurplusInfo.visible
      "
      class="app-container-flex"
    >
      <NewFullScreen
        v-model="showDialog"
        title="资产入库单明细"
        :needOperateAffair="true"
        :operateAffairData="affairTableInfo"
        :needReturn="!$route.query.processInstanceId"
        @returnBack="returnBack"
      >
        <template v-slot:full-button>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="canPrint"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
          <el-button
            v-if="
              infoList.data.status === 3 &&
              $permission('assetStoreOrderDetail:exportExcel')
            "
            @click="exportExcel"
            >导出excel</el-button
          >
          <el-button v-if="canUpdate" @click="update">修改</el-button>
          <el-button v-if="canSubmit" @click="submit">提交</el-button>
          <el-button v-if="autoBuild" @click="_autoBuildCard"
            >批量建卡</el-button
          >
          <el-button @click="recall" v-if="canRecall">撤回</el-button>
          <el-button @click="approve" v-if="canAccept">批准</el-button>
          <el-button @click="reject" v-if="canReject">驳回</el-button>
          <el-button @click="refuse" v-if="canRefuse">拒绝</el-button>
          <el-button @click="salesReview" v-if="canSalesReview">销审</el-button>
        </template>

        <div class="model-panel">
          <div class="model-panel-title">
            <p>{{ $t('basic_information') }}</p>
          </div>
          <div class="model-panel-body">
            <basic-information :info="infoList">
              <template v-slot:basic-invoiceNumber>
                <div
                  v-if="
                    infoList.data.invoiceNumberList &&
                    infoList.data.invoiceNumberList.length > 0
                  "
                >
                  <span
                    v-for="(item, index) in infoList.data.invoiceNumberList"
                    :key="index"
                  >
                    <a v-if="index <= 1">{{ item }}</a>
                    <span
                      v-if="
                        index < 1 && infoList.data.invoiceNumberList.length > 1
                      "
                      >,</span
                    >
                  </span>
                  <el-dropdown
                    v-if="infoList.data.invoiceNumberList.length > 2"
                  >
                    <span class="el-dropdown-link">
                      更多
                      <i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <template #dropdown>
                      <el-dropdown-menu>
                        <el-dropdown-item
                          v-for="(item, index) in infoList.data
                            .invoiceNumberList"
                          :key="index"
                          >{{ item }}</el-dropdown-item
                        >
                      </el-dropdown-menu>
                    </template>
                  </el-dropdown>
                </div>
                <span v-else>-</span>
              </template>
            </basic-information>
          </div>
        </div>

        <div class="model-panel">
          <div class="model-panel-title">
            <Tooltip :text="$t('detailInfo')"></Tooltip>
          </div>
          <div class="model-panel-body">
            <div class="flex_full_item">
              <!-- 表格 -->
              <page-table
                :refresh="tableInfo.refresh"
                :init-curpage="tableInfo.initCurpage"
                v-model:data="tableInfo.data"
                :pager="false"
                :summary="true"
                :check-box="false"
                :tab-index="true"
                :summary-field-list="tableInfo.summaryFieldList"
                :field-list="tableInfo.fieldList"
                :handle="tableInfo.handle"
                :isDynamic="true"
              >
              </page-table>
            </div>
          </div>
        </div>
      </NewFullScreen>
    </div>
    <DeviceStoreOrderModify
      v-if="modifyInfo.visible"
      v-model:visible="modifyInfo.visible"
      :title="modifyInfo.title"
      :order-id="modifyInfo.orderId"
      @returnModify="refreshDetail"
    />
    <chose-printer :visible="printerInfo.visible" @callBack="printerCallBack" />
    <!-- 入库选择弹窗 -->
    <auto-build-card
      v-if="buildCardDialogInfo.visible"
      :show-dept="false"
      v-model:show-dialog="buildCardDialogInfo.visible"
      @updateFormInfo="updateFormInfo"
    ></auto-build-card>
    <modifyReceive
      v-if="modifyReceiveInfo.visible"
      v-model:visible="modifyReceiveInfo.visible"
      :title="modifyReceiveInfo.title"
      :receive-order="modifyReceiveInfo.receiveOrder"
      :order-id="modifyReceiveInfo.orderId"
      @returnModify="refreshDetail"
    />
    <modifyContract
      v-if="modifyByContractInfo.visible"
      v-model:visible="modifyByContractInfo.visible"
      :title="modifyByContractInfo.title"
      :contract-order="modifyByContractInfo.contractOrder"
      :order-id="modifyByContractInfo.orderId"
      @returnModify="refreshDetail"
    />
    <!-- 批量建卡 -->
    <BuildAssetCard
      v-if="buildAssetCardInfo.visible"
      v-model:visible="buildAssetCardInfo.visible"
      :tableRow="buildAssetCardInfo.tableRow"
      :currentAccountingInterval="buildAssetCardInfo.currentAccountingInterval"
      :type="buildAssetCardInfo.type"
      @returnModify="refreshDetail"
    ></BuildAssetCard>
    <CapitalSourceAdjustAssetStore
      v-if="capitalSourceAdjustInfo.visible"
      :disabled="true"
      v-model:show-dialog="capitalSourceAdjustInfo.visible"
      :right-data="capitalSourceAdjustInfo.rightData"
    />
    <modify-surplus
      v-if="modifySurplusInfo.visible"
      v-model:visible="modifySurplusInfo.visible"
      :orderId="modifySurplusInfo.id"
      :surplusId="modifySurplusInfo.surplusId"
      :surplusNo="modifySurplusInfo.surplusNo"
      :title="modifySurplusInfo.title"
      :type="''"
      @returnModify="returnModify"
    />
  </div>
</template>

<script setup name="assetStoreOrderDetail">
import {
  getAssetStoreOrderDetailCustomizeList,
  detailAssetStoreOrder,
  submitAssetStoreOrder,
  revokeAssetStoreOrder,
  storeAssetStoreOrder,
  exportExcelAssetStoreOrder,
  getAssetStorePrint,
  assetStoreOrdersBuild,
  approvedAssetStore,
  refuseAssetStore,
  rejectAssetStore,
  cancelCheckStoreOrder,
  batchBuildByAssetStoreOrders,
} from '@/api/asset'
import { orderOpAffairAll } from '@/api/affair'
import { getCustomizeSetting } from '@/api/customize'
const modifyReceive = defineAsyncComponent(() => import('./modifyReceive'))
const modifyContract = defineAsyncComponent(() => import('./modifyContract'))
const DeviceStoreOrderModify = defineAsyncComponent(() => import('./modify'))
const autoBuildCard = defineAsyncComponent(() =>
  import('@/views/asset/components/autoBuildCard')
)
const CapitalSourceAdjustAssetStore = defineAsyncComponent(() =>
  import('../../components/capitalSourceAdjustAssetStore')
)
const modifySurplus = defineAsyncComponent(() => import('./modifySurplus'))
import { getCurrentFiscalPeriod } from '@/api/core'
import { doPrint } from '@/utils/exportUtil.js'
import { selectByCodeAndDept } from '@/api/report.js'
import { updatePrintCount } from '@/api/mapping'

const { proxy } = getCurrentInstance()
const emits = defineEmits()
const props = defineProps(['visible', 'tableRow', 'id'])
const infoList = ref({
  data: {},
  fieldList: [
    { label: '单号', value: 'orderNo', type: 'text' },
    { label: '部门', value: 'deptName', type: 'text' },
    { label: '仓库', value: 'depotName', type: 'text' },
    { label: '供应商', value: 'supplierName', type: 'text' },
    { label: '收货单号', value: 'receiveNo', type: 'text' },
    { label: '合同单号', value: 'contractNo', type: 'text' },
    { label: '入库方式', value: 'increaseTypeValue', type: 'text' },
    { label: '建卡状态', value: 'buildCardStatusValue', type: 'text' },
    { label: '状态', value: 'statusValue', type: 'text' },
    { label: '入库人', value: 'storeUserName', type: 'text' },
    { label: '入库时间', value: 'storeTime', type: 'text' },
    { label: '备注', value: 'remark', type: 'text' },
  ],
})
// 过滤相关配置
const filterInfo = ref({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: 'EQUALS',
        queryCategory: 'AND',
        value: props.id || props.tableRow.id,
      },
    },
    queryParams: {
      sourceType: 52,
      sourceId: '',
    },
  },
})
const buildAssetCardInfo = ref({
  visible: false,
  tableRow: [],
  type: '',
})

const modifyInfo = ref({
  visible: false,
  title: '',
})
const modifyReceiveInfo = ref({
  visible: false,
  orderId: '',
  receiveOrder: {},
  title: '',
})
const modifyByContractInfo = ref({
  visible: false,
  orderId: '',
  receiveOrder: {},
  title: '',
})
const capitalSourceAdjustInfo = ref({
  visible: false,
  row: {},
  leftData: [],
  rightData: [],
})
// 表格相关
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  summaryFieldList: [
    { value: 'qty', formatter: proxy.$fn.qtyFormatter },
    { value: 'sumAmount', formatter: proxy.$fn.TripartiteMethod },
  ],
  fieldList: [],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '120',
    btList: [
      {
        label: '资金来源',
        event: adjustAmount,
        show: true,
      },
    ],
  },
})
const affairTableInfo = ref({
  api: orderOpAffairAll,
  query: {
    orderType: 66,
    orderId: props.id || props.tableRow.id,
    sort: 'operate_time desc',
  },
})
const individualInfo = ref({
  visible: false,
  query: {},
  info: {},
})
const printerInfo = ref({
  visible: false,
  data: {},
})
const modifySurplusInfo = ref({
  visible: false,
  id: '',
  surplusId: '',
  title: '',
  surplusNo: '',
})
const formInfoData = ref({})
const buildCardDialogInfo = ref({
  visible: false,
  type: '',
})

const showDialog = computed({
  get() {
    return props.visible
  },
  set(newValue) {
    emits('update:visible', newValue) // 更新父组件visible
  },
})
const canPrint = computed(() => {
  return (
    proxy.$permission('assetStoreOrder:print') &&
    infoList.value.data.status === 3
  )
})
const canUpdate = computed(() => {
  return (
    (proxy.$permission('assetStoreOrder:update') &&
      infoList.value.data.status === 1) ||
    infoList.value.data.status === 7
  )
})
const canSubmit = computed(() => {
  return (
    (proxy.$permission('assetStoreOrder:submit') &&
      infoList.value.data.status === 1) ||
    infoList.value.data.status === 7
  )
})
const canExecute = computed(() => {
  return (
    proxy.$permission('assetStoreOrder:store') &&
    infoList.value.data.status === 2
  )
})
const autoBuild = computed(() => {
  return (
    proxy.$permission('assetStore:buildCard') &&
    proxy.$store.state.permission.systemConfig.auto_build_card == 0 &&
    (infoList.value.data.buildCardStatus === 1 ||
      infoList.value.data.buildCardStatus === 2)
  )
})
// 批准
const canAccept = computed(() => {
  return (
    proxy.$permission('assetStoreOrder:approve') &&
    proxy.$store.state.permission.systemConfig.allow_assets_store_approval ==
      1 &&
    infoList.value.data.status === 4
  )
})
// 驳回
const canReject = computed(() => {
  return (
    proxy.$permission('assetStoreOrder:reject') &&
    proxy.$store.state.permission.systemConfig.allow_assets_store_approval ==
      1 &&
    infoList.value.data.status === 4
  )
})
// 拒绝
const canRefuse = computed(() => {
  return (
    proxy.$permission('assetStoreOrder:refuse') &&
    proxy.$store.state.permission.systemConfig.allow_assets_store_approval ==
      1 &&
    infoList.value.data.status === 4
  )
})
// 撤回
const canRecall = computed(() => {
  return (
    proxy.$permission('assetStoreOrder:recall') &&
    (infoList.value.data.status === 4 ||
      (infoList.value.data.status === 3 &&
        proxy.$store.state.permission.systemConfig
          .allow_assets_store_approval == 0))
  )
})
// 销审
const canSalesReview = computed(() => {
  return (
    proxy.$permission('assetStoreOrder:salesReview') &&
    infoList.value.data.status === 3 &&
    proxy.$store.state.permission.systemConfig.allow_assets_store_approval != 0
  )
})
function adjustAmount(row) {
  capitalSourceAdjustInfo.value.rightData = row.capitalSourceList || []
  capitalSourceAdjustInfo.value.visible = true
  capitalSourceAdjustInfo.value.row = row
}
setData()

function setData() {
  let obj = {
    price: {
      label: '单价',
      value: 'price',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('assetStoreOrder:price'),
      show: false,
      hidden: true,
    },
    sumAmount: {
      label: '总金额',
      value: 'sumAmount',
      formatter: proxy.$fn.TripartiteMethod,
      permission: !proxy.$permission('assetStoreOrder:price'),
      show: false,
      hidden: true,
    },
    orderNo: {
      label: '单号',
      value: 'orderNo',
      componentType: 'input',
      show: false,
      type: 'column',
      hidden: true,
    },
    preQty: {
      label: '可入库数量',
      value: 'preQty',
      type: 'column',
      componentType: 'column',
      formatter: proxy.$fn.qtyFixedFormatter,
      show: false,
      hidden: true,
    },
    receiveQty: {
      label: '收货数量',
      value: 'receiveQty',
      type: 'column',
      componentType: 'column',
      formatter: proxy.$fn.qtyFixedFormatter,
      show: false,
      hidden: true,
    },
  }
  tableInfo.value.fieldList = Object.values({
    ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
    ...obj,
  })
  getCustomize()
}
const templateArr = ref([])
const popoverVisible = ref(false)
//打印
function print() {
  selectByCodeAndDept({
    tempCode: 'assetStoreDetail',
    deptId: infoList.value.data.deptId,
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data
      popoverVisible.value = true
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        proxy.$refs.popoverShow.hidePopover()
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {
            orderId: props.id || props.tableRow.id,
          },
          callback: printCallback,
          data: {},
        })
      }
    }
  })
}
function printCallback() {
  try {
    // 打印成功增加打印次数
    updatePrintCount({
      orderNo: infoList.value.data.orderNo,
      orderId: props.id || props.tableRow.id,
      orderType: 64,
    })
  } catch (error) {}
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      orderId: props.id || props.tableRow.id,
    },
    callback: printCallback,
    data: {},
  })
  popoverVisible.value = false
}
function getPrintData(temp) {
  let params = {
    tableKey:
      'assetStoreOrderDetail-com.slip.spd.entity.vo.device.store.AssetStoreOrderDetailVO',
    orderIds: [props.id || props.tableRow.id],
  }
  getAssetStorePrint(params).then((res) => {
    if (res.success && res) {
      let data = proxy.$fn.deepClone(res.data)
      let newData = data.map((item) => {
        return {
          ...item,
          ...item.orderInfo,
        }
      })
      proxy.$lodop.preview(temp, newData)
    }
  })
}
function showCardDialog() {
  getCurrentFiscalPeriod(2).then((resp) => {
    if (resp && resp.success && resp.data) {
      buildAssetCardInfo.value.currentAccountingInterval = resp.data.startDate
    }
  })
  buildAssetCardInfo.value.tableRow = [infoList.value.data]
  buildAssetCardInfo.value.type = 'store-store'
  buildAssetCardInfo.value.visible = true
}
function _autoBuildCard() {
  //批量建卡
  batchBuildByAssetStoreOrders([infoList.value.data.id]).then((res) => {
    if (res.success) {
      setData()
    }
  })
  // 批量建卡
  /*  getCurrentFiscalPeriod(2).then((resp) => {
    if (resp && resp.success && resp.data) {
      buildAssetCardInfo.value.currentAccountingInterval = resp.data.startDate
    }
  })
  buildAssetCardInfo.value.tableRow = [infoList.value.data]
  buildAssetCardInfo.value.type = 'store-build'
  buildAssetCardInfo.value.visible = true */
}
function updateFormInfo(val) {
  if (val) {
    formInfoData.value = Object.assign(formInfoData.value, val)
  }
  buildCard()
}
function buildCard() {
  const api =
    buildCardDialogInfo.value.type === 'store'
      ? storeAssetStoreOrder
      : buildCardDialogInfo.value.type === 'build'
      ? assetStoreOrdersBuild
      : ''
  api(formInfoData.value).then((res) => {
    if (res && res.success) {
      buildCardDialogInfo.value.visible = false
      formInfoData.value.data = {}
      refreshDetail()
    }
  })
}
//提交
function submit() {
  let data = {
    flowTaskCommentDto: { approvalType: 'submit' },
    processDefinitionKey: 'assetStore',
    orderIds: [infoList.value.data.id],
  }
  submitAssetStoreOrder(data).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function store() {
  storeAssetStoreOrder([{ orderSourceId: infoList.value.data.id }]).then(
    (resp) => {
      if (resp && resp.success) {
        refreshDetail()
      }
    }
  )
}
// 撤回
function recall() {
  revokeAssetStoreOrder([infoList.value.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      refreshDetail()
      proxy.$message.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      proxy.$message.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
function approve() {
  approvedAssetStore({ orderId: infoList.value.data.id }).then((resp) => {
    if (resp && resp.success) {
      refreshDetail()
    }
  })
}
function reject() {
  btnFlow(infoList.value.data, 'reject')
}
function refuse() {
  btnFlow(infoList.value.data, 'refuse')
}
// 按钮审批原因弹窗
function btnFlow(row, code) {
  let currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = rejectAssetStore
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = refuseAssetStore
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderId: row.id,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          refreshDetail()
        }
      })
    })
}
// 销审
function salesReview() {
  cancelCheckStoreOrder([infoList.value.data.id]).then((res) => {
    if (res && res.success) {
      if (proxy.$route.query.processInstanceId) {
        proxy.$fn.setFlowPath(proxy)
        return
      }
      refreshDetail()
      proxy.$message.success({
        message: '操作成功',
        duration: 3000,
        showClose: true,
      })
    } else {
      proxy.$message.error({
        message: res.msg,
        duration: 3000,
        showClose: true,
      })
    }
  })
}
//导出excel
function exportExcel() {
  exportExcelAssetStoreOrder(filterInfo.value.query).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
function refreshDetail() {
  getMain()
}
function returnBack() {
  emits('returnBack', false)
}
function showDetail(row) {
  let ids
  if (row.groupConcatIds) {
    //未定义表示没有分组条件
    ids = row.groupConcatIds
  } else {
    ids = '' + row.id
  }
  individualInfo.value.query = {
    id: {
      queryType: 'IN',
      queryCategory: 'AND',
      value: ids,
    },
    orderId: {
      queryType: 'EQUALS',
      queryCategory: 'AND',
      value: props.id || props.tableRow.id,
    },
  }
  individualInfo.value.info = row
  individualInfo.value.visible = true
}
function getMain() {
  detailAssetStoreOrder(props.id || props.tableRow.id).then((resp) => {
    if (resp && resp.success) {
      infoList.value.data = resp.data
      filterInfo.value.query.queryParams.sourceId = resp.data.sourceId
      infoList.value.data.invoiceNumberList = infoList.value.data.invoiceNumber
        ? infoList.value.data.invoiceNumber.indexOf(',') !== -1
          ? infoList.value.data.invoiceNumber.split(',')
          : [infoList.value.data.invoiceNumber]
        : []
      getList()
    }
  })
}
function ifRenderValue() {
  return infoList.value.data.status === 2 || infoList.value.data.status === 3
}
function update() {
  if (infoList.value.data.receiveId && infoList.value.data.receiveId !== -2) {
    modifyReceiveInfo.value.orderId = infoList.value.data.id
    modifyReceiveInfo.value.title = '修改入库单'
    modifyReceiveInfo.value.visible = true
    modifyReceiveInfo.value.receiveOrder = {
      id: infoList.value.data.receiveId,
    }
  } else if (
    infoList.value.data.contractId &&
    infoList.value.data.contractId !== -2
  ) {
    modifyByContractInfo.value.orderId = infoList.value.data.id
    modifyByContractInfo.value.title = '修改入库单'
    modifyByContractInfo.value.visible = true
    modifyByContractInfo.value.contractOrder = {
      id: infoList.value.data.contractId,
    }
  } else if (infoList.value.data.sourceType === 52) {
    modifySurplusInfo.value.visible = true
    modifySurplusInfo.value.id = infoList.value.data.id
    modifySurplusInfo.value.surplusId = infoList.value.data.sourceId
    modifySurplusInfo.value.surplusNo = infoList.value.data.sourceOrderNo
    modifySurplusInfo.value.title = '修改入库单'
  } else {
    modifyInfo.value.orderId = infoList.value.data.id
    modifyInfo.value.title = '修改入库单'
    modifyInfo.value.visible = true
  }
}
function getList() {
  getAssetStoreOrderDetailCustomizeList(filterInfo.value.query).then((resp) => {
    if (resp && resp.success) {
      tableInfo.value.data = resp.data
    }
  })
}

function printerCallBack(printer) {
  if (printer !== false) {
    proxy.$print.buildRenderBarCode(printerInfo.value.data, printer)
  }
  printerInfo.value.visible = false
}
function getCustomize() {
  let param = {
    tableKey:
      'assetStoreOrderDetail-com.slip.spd.entity.vo.device.store.AssetStoreOrderDetailVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let obj = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )
      tableInfo.value.fieldList = obj.fieldList
      getMain()
    }
  })
}
</script>

<style scoped></style>
